#include<stdio.h>
#include<math.h>
#define maxno 1000

double ffunction(double x);

int main()
{

	int n,i,j,k;
	double sum=0,max=1.0,min=-1.0,value=0.0,x[maxno],y[maxno],term=0.0,t=0.0,sum1=0,temp;
	FILE *fp;
	
	printf("\n Enter the degree N of the polynomial(Number of Iterations) :\n");
	scanf("%d",&n);

	fp=fopen("Plot_Lagrange_graph.txt","w");
	if(!fp)
	{
		printf("\n File does not exist\n");
		exit(0);
	}
	i=0;
	value=(max-min)/n;
	while(min<=max+value)
	{
		x[i]=min;
//		y[i]=ffunction(x[i]);
//		fprintf(fp,"\n%lf\t%lf",x[i],y[i]);
		min=min+value;
		i++;
	}
//	fclose(fp);
//	fp=fopen(OuputFile,"w");
/*	if(!fp)
	{
		printf("\n File does not exist\n");
		exit(0);
	}
*/	
// make the nodes ,store the function values, initialize the array
	printf("\nX \t f(x)"); 
	for(k=0;k<=i;k++)
	{
		t=x[k];
		sum = 0;
		//sum1= 0;
		//term = 1;
		
		for(i=0;i<n;i++)
		{
			term = y[i];
			//temp=1;
			//printf("\n %lf",y[i]);
			for(j=0;j<n;j++)
			{
				if(i!=j)
					term = term * ((t-x[j])/(x[i]-x[j]));
					
			}
			sum = sum + term;
			//sum1= sum1+temp;
			//printf("\n%lf\t%lf",t,sum);
			//fprintf(fp,"\n%lf\t%lf",t,sum);
		}

		printf("\n%lf\t%lf",t,sum);
		//printf("\n%lf\t%lf",t,sum1);
		fprintf(fp,"\n%lf\t%lf",t,sum);
	}
	printf("\n");
	fclose(fp);
	return(0);
}



